package cn.org.eshow.dao.hibernate;

import cn.org.eshow.bean.query.FavoriteQuery;
import cn.org.eshow.common.dao.EnhancedRule;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.FavoriteDao;
import cn.org.eshow.model.Favorite;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("favoriteDao")
public class FavoriteDaoHibernate extends GenericDaoHibernate<Favorite, Integer> implements FavoriteDao {

    public FavoriteDaoHibernate() {
        super(Favorite.class);
    }

    public Page<Favorite> search(FavoriteQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        if (query != null) {
            rule.setOffset(query.getOffset());
            rule.setPageSize(query.getPagesize());
        }
        return page(rule);
    }

    public List<Favorite> list(FavoriteQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return list(rule);
    }

    public long count(FavoriteQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return count(Favorite.class, rule);
    }

    public EnhancedRule setRule(EnhancedRule rule, FavoriteQuery query) {
        if (query != null) {
            if (query.startAddTime != null) {
                rule.add(Restrictions.ge("addTime", query.startAddTime));
            }
            if (query.endAddTime != null) {
                rule.add(Restrictions.le("addTime", query.endAddTime));
            }
            if (query.startUpdateTime != null) {
                rule.add(Restrictions.ge("updateTime", query.startUpdateTime));
            }
            if (query.endUpdateTime != null) {
                rule.add(Restrictions.le("updateTime", query.endUpdateTime));
            }
            if (query.enabled != null) {
                rule.add(Restrictions.eq("enabled", query.enabled));
            }
            if (query.productId != null) {
                rule.add(Restrictions.eq("product.id", query.productId));
            }
            if (query.userId != null) {
                rule.add(Restrictions.eq("user.id", query.userId));
            }
            if (!StringUtils.isEmpty(query.getOrder())) {
                rule.addOrder(query.getDesc() ? Order.desc(query.getOrder()) : Order.asc(query.getOrder()));
            }
        }
        return rule;
    }

}
